package io.wmy.supex.common.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.io.Writer;

public class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private static ObjectMapper objectmapper = new ObjectMapper();


    public static String objectToJson(Object object) {
        Writer strWriter = new StringWriter();
        try {
            objectmapper.writeValue(strWriter, object);
        } catch (Exception e) {
            logger.info("JSON解析出错", e);
        }
        return strWriter.toString();
    }

    public static Object jsonToEntity(Object object, String json) {
        try {
            return objectmapper.readValue(json, object.getClass());
        } catch (Exception e) {
            logger.info("JSON解析出错", e);
            return null;
        }
    }

    public static String objectToJson(Object object, boolean isFormat) {
        return isFormat ? objectToFormatJson(object) : objectToJson(object);
    }

    public static String objectToFormatJson(Object object) {
        Writer strWriter = new StringWriter();
        try {
            objectmapper.writerWithDefaultPrettyPrinter().writeValue(strWriter, object);
        } catch (Exception e) {
            logger.info("JSON解析出错", e);
        }
        return strWriter.toString();
    }

    public static Object jsonToEntity(Class<?> clazz, String json) {
        try {
            return objectmapper.readValue(json, clazz);
        } catch (Exception e) {
            logger.info("JSON解析出错", e);
            return null;
        }
    }

    public static String jsonToStringByKey(String json, String key) {
        try {
            JsonNode rootNode = objectmapper.readTree(json);
            String value = rootNode.path(key).asText();
            return value;
        } catch (Exception e) {
            logger.info("JSON解析出错", e);
            return null;
        }
    }
}
